<template>
  <div class="card">
    <el-row :gutter="14" justify="start" style="align-items: center;margin:15px 0;" >
      <el-col :span="4" style="display: flex;align-items: center">
        <label style="width: 80px;">订单号:</label>
        <el-input style="width: 140px" name="ddid" v-model="dingdan.ddid" placeholder="请填写订单号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center">
        <label style="width: 80px;">手机号:</label>
        <el-input style="width: 140px" name="phone" v-model="dingdan.phone" placeholder="请填写手机号"></el-input>
      </el-col>
      <el-col :span="8" >
        <div class="block" style="display: flex;align-items: center">
          <span class="status-label2" >下单时间:</span>
          <el-date-picker
              v-model="psks"
              type="datetimerange"
              :shortcuts="shortcuts"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 300px; margin-left: 8px;"
          />
        </div>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="handleQuery" style="border-radius: 5px">查询</el-button>
      </el-col>
      <el-col :span="2">
        <el-button type="info" @click="reset" style="border-radius: 5px">重置</el-button>
      </el-col>
    </el-row>

    <!--表格-->
    <el-row justify="start" >
      <el-table
          :data="dingdanList"
          style="width: 100%;"
      >
        <el-table-column prop="ddid" label="订单id"></el-table-column>
        <el-table-column prop="ddzt" label="订单状态"></el-table-column>
        <el-table-column prop="yhid" label="用户id"></el-table-column>
        <el-table-column prop="userInfo.phone" label="手机号"></el-table-column>
        <el-table-column prop="dddz" label="地址"></el-table-column>
        <el-table-column prop="ddsj" label="下单时间"></el-table-column>
        <el-table-column prop="tprice" label="总价"></el-table-column>
        <el-table-column label="操作" >
          <template #default="scope" >
            <div>
              <el-button type="info" style="padding:1px;border-radius: 4px" @click="showDetailDialog(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
  </div>


  <!--  详情页面  -->
  <el-dialog v-model="detailDialogVisible" title="订单信息" width="60%" top="10vh" style="height: 75%" destroy-on-close>
    <show-d-d-x-q
        ref="detailPageRef"
        @flushPage="reset"
        @closeDialog="detailDialogVisible = false">
    </show-d-d-x-q>
  </el-dialog>
  <!-- 新增 dialog-->
  <el-dialog v-model="addDialogVisible" title="新增订单" width="40%" top="2vh" destroy-on-close>
    <add-dingdan
        @flushPage="reset"
        @closeDialog="addDialogVisible = false">
    </add-dingdan>
  </el-dialog>


</template>

<script setup >
import {nextTick, onMounted, reactive, ref} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import AddDingdan from "./AddDingdan.vue";
import ShowDDXQ from "../ddxiangqing/ShowDDXQ.vue";
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')))
const dingdan = reactive({
  ddid: '',
  psks: '',
  yhid: '',
})
const dingdanList = ref();  // 订单信息列表
// 标记是否为用户主动查询（初始为 false）
const isUserQuery = ref(false);

onMounted(async () => {
  isUserQuery.value = false;
  await doList();
  await showList();
});

const doList = async () => {
  dingdanList.value = [];
  const url = dingdan.ddid ? `/api/dingdan/${dingdan.ddid}` : '/api/dingdan';
  const {data} = await axios.get(url)
  if(data.code === 200){
    console.log(dingdan.ddid)
    dingdanList.value = dingdan.ddid
        ? [data.data]
        : data.data;
    // 只有用户主动查询时才显示成功提示
    if (isUserQuery.value) {
      /*ElMessage.success('查询成功');*/
      await showList();
    }
  }else{
    // 错误提示始终显示（无论是否用户操作）
    ElMessage.error(data.message);
  }
}

const showList = async () => {
  // 先确保订单数据已加载
  if (!dingdanList.value || dingdanList.value.length === 0) return;

  // 收集所有订单中的用户ID，去重
  const yhids = (dingdanList.value.map(order => order.yhid));

  if (yhids.length === 0) return;

  try {
    // 调用后端批量查询用户的接口
    const { data } = await axios.post('/api/dingdan/users',  yhids);

    if (data.code === 200) {
      // 构建用户ID到用户信息的映射表
      const userMap = data.data.reduce((map, user) => {
        map[user.yhid] = user;
        return map;
      }, {});

      // 将用户信息关联到对应的订单
      dingdanList.value.forEach(order => {
        if (userMap[order.yhid]) {
          order.userInfo = userMap[order.yhid];
        }
      });
      if(isUserQuery.value){
        ElMessage.success('用户信息加载成功');
      }
    } else {
      ElMessage.error(data.message);
    }
  } catch (error) {
    ElMessage.error('加载用户信息失败');
    console.error(error);
  }
}

const reset = async () => {
  dingdan.ddid = '';
  isUserQuery.value = true; // 标记为用户操作
  await doList();
  await showList();
}
// 查询按钮点击：用户主动操作，需要显示提示
const handleQuery = async () => {
  isUserQuery.value = true; // 标记为用户操作
  await doList();
  // showList();
}

const addDialogVisible = ref(false)
const showAddDialog = () => {
  addDialogVisible.value = true;
}


const detailDialogVisible = ref(false)
const detailPageRef = ref();
const showDetailDialog = (row) => {
  detailDialogVisible.value = true;
  nextTick(()=>{
    console.log("2222",row);
    detailPageRef.value.handleShowData(row);
    console.log("1111",row);
  })
}

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]

</script>

<style scoped>
.card{
  margin-left: -50px;
  margin-right: -30px;
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0,0,0, .12);
}
#head{
  display: flex;
  width: 60%;
  justify-content: center;
  align-items: center;
  height: 50px;
  text-align: center;
}
.status-col {
  font-family: "Inter", "Helvetica Neue", Arial, "PingFang SC", "Hiragino Sans GB",
  "Microsoft YaHei", "微软雅黑", sans-serif;
  font-size: 15px;
  letter-spacing: 1px;
}
.status-col:first-child{
  border-bottom-left-radius: 5px;
  border-top-left-radius: 5px;
}
.status-col:last-child{
  border-bottom-right-radius: 5px;
  border-top-right-radius: 5px;
}
.status-label {
  display: inline;
  width: 100%;
  height: 100%;
  line-height: 26px;
  text-align: center;
  cursor: pointer;
}
.status-label2 {
  display: inline-block;
  width: 80px;        /* 固定标签宽度，让文字对齐 */
  text-align: right;  /* 文字右对齐 */
  margin-right: 8px;  /* 和输入框/选择器保持间距 */
}

</style>